<template>
  <Dialog title="查询条件设置" v-model="visibleDialog" width="400px">
    <div class="e-filter-search" ref="eFilterSearchRef">
      <div
        v-for="(item, index) in visibleColumns"
        :key="index + '#' + item.prop"
        class="search-list"
      >
        <div class="search-list-item flex items-center justify-between">
          <span class="flex items-center">
            <Icon style="margin-right: 10px" icon="ep:operation" />
            {{ item.label }}
          </span>
          <span class="cursor-pointer" @click="handleChangeShow(item.prop)">
            <el-icon v-if="item.isFilter"><View /></el-icon>
            <el-icon v-else><Hide /></el-icon>
          </span>
        </div>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="saveLoading" @click="handleConfirm">确认</el-button>
        <el-button type="primary" @click="handleReset">重置</el-button>
      </span>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
  import { ref, nextTick, PropType } from 'vue'
  import { propTypes } from '@/utils/propTypes'
  import { View, Hide } from '@element-plus/icons-vue'
  // import { saveListSetting } from '@/api/system/user'
  import Sortable from 'sortablejs'
import { ElMessage } from 'element-plus'
  interface columnsType {
    label: string
    prop: string
    isFilter: boolean
    filterConfig: {
      type: string
      placeholder?: string
      options?: Array<{ label: string; value: any }>
      multiple?: boolean
    }
  }
  defineOptions({ name: 'EFilterSearch' })
  const emit = defineEmits(['confirm'])
  const props = defineProps({
    columns: propTypes.array.def(() => []),
    uniqueKey: {
      type: String,
      default: ''
    },
    saveSettingFunc: {
      type: Function as PropType<() => Promise<any>>,
      default: undefined
    }
  })

  const visibleColumns = ref<columnsType[]>([])

  const visibleDialog = ref(false)

  const open = (columns: columnsType[]) => {
    debugger
    visibleDialog.value = true
    visibleColumns.value = [...columns].map((item: columnsType) => {
      let child = { ...item }
      return {
        ...child
      }
    })
    nextTick(() => initDialogTableSortable())
  }

  // 弹窗表格引用
  const eFilterSearchRef = ref()
  // 初始化表格拖拽排序
  const initDialogTableSortable = () => {
    nextTick(() => {
      const el = eFilterSearchRef.value
      if (!el) return

      Sortable.create(el, {
        animation: 300,
        handle: '.search-list-item',
        ghostClass: 'sortable-ghost',
        onEnd: ({ newIndex, oldIndex }) => {
          if (newIndex === undefined || oldIndex === undefined) return
          const newData = [...visibleColumns.value]
          const [moved] = newData.splice(oldIndex, 1)
          newData.splice(newIndex, 0, moved)
          visibleColumns.value = newData
        }
      })
    })
  }

  
  const handleChangeShow = (prop: string) => {
    visibleColumns.value.forEach((item) => {
      if (item.prop === prop) {
        item.isFilter = !item.isFilter
      }
    })
  }
  const handleCancel = () => {
    visibleDialog.value = false
  }

  const saveLoading = ref(false)
  const handleConfirm = () => {
    saveLoading.value = true
    // 保存时重置排序号
    let settingValue = visibleColumns.value.map((col, index) => ({ ...col, sortNo: index }))
    // 保存列表设置到服务器
    if ( !props.uniqueKey&&!props.saveListSettingFunc) return
    props.saveSettingFunc?.({
      settingKey: props.uniqueKey,
      settingValue: JSON.stringify(settingValue)
    })
      .then((res) => {
        if (res) {
          ElMessage.success('保存成功')
          emit('confirm', settingValue)
          visibleDialog.value = false
        } else {
          ElMessage.error('保存失败')
        }
      })
      .finally(() => {
        saveLoading.value = false
      })
  }
  const handleReset = () => {
    visibleColumns.value = [...props.columns].map((item: columnsType) => {
      let child = { ...item }
      return {
        ...child
      }
    })
  }
  defineExpose({ open })
</script>
<style lang="scss" scoped>
  .e-filter-search {
    .search-list {
      &:nth-child(odd) {
        background-color: #f8fafe;
      }
      .search-list-item {
        height: 23px;
        padding: 12px;
      }
    }
  }
</style>
